package com.cuiweiyou.happypaint.util;

public class StringUtil {

    /**
     * 字节数组转16进制字符串原始指令
     *
     * @param bytes
     * @return
     */
    public static String bytesToHexString(byte[] bytes) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < bytes.length; i++) {
            String hex = Integer.toHexString(0xFF & bytes[i]);
            if (hex.length() == 1) {
                sb.append('0');
            }
            sb.append(hex);
        }
        String result = sb.toString();

        return result;
    }

    /**
     * 16进制指令字符串转字节数组
     *
     * @param cmd
     * @return
     */
    public static byte[] hexStringToByteArray(String cmd) {
        if (cmd == null || cmd.equals("")) {
            return null;
        }
        cmd = cmd.toUpperCase();

        int len = cmd.length();
        byte[] bytes = new byte[len / 2];
        for (int i = 0; i < len; i += 2) {
            bytes[i / 2] = (byte) ((Character.digit(cmd.charAt(i), 16) << 4) + Character.digit(cmd.charAt(i + 1), 16));
        }

        return bytes;
    }
}
